package com.itheima.web;

import com.itheima.pojo.Contact;
import com.itheima.service.ContactService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

/**
 * @author slstart
 * @create 2021-05-23 19:17
 */
@WebServlet("/contact")
public class ContactServlet extends BaseServlet {
    private ContactService contactService = new ContactService();

    public void findAll(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        List<Contact> list = contactService.findAll();
        request.setAttribute("list",list);
        request.getRequestDispatcher("/contact/list.jsp").forward(request,response);
    }

    public void add(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, IOException {
        Map<String, String[]> map = request.getParameterMap();
        Contact contact = new Contact();
        BeanUtils.populate(contact,map);
        boolean flag = contactService.addContact(contact);
        if(flag){
            response.sendRedirect("/contact?method=findAll");
        }
    }

    public void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String id = request.getParameter("id");
        Contact contact = contactService.findById(id);
        request.setAttribute("contact",contact);

        request.getRequestDispatcher("/contact/update.jsp").forward(request,response);
    }

    public void update(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, IOException {
        Map<String, String[]> map = request.getParameterMap();
        Contact contact = new Contact();
        BeanUtils.populate(contact,map);
        boolean flag = contactService.updateContact(contact);
        if(flag){
            response.sendRedirect("/contact?method=findAll");
        }
    }
    public void deleteContactById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        boolean flag = contactService.deleteById(id);
        if(flag){
            response.sendRedirect("/contact?method=findAll");
        }

    }
}
